//
//  ChangePhoneTwo.swift
//  LeGou
//
//  Created by lxm on 2022/8/3.
//

import UIKit

class ChangePhoneTwo: ZMViewController {

    //MARK:--------------------属性--------------------
    
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var phoneTxt: UITextField!
    @IBOutlet weak var codeTxt: UITextField!
    @IBOutlet weak var codeBtn: CountButton!
    @IBOutlet weak var nextBtn: UIButton!
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
    }
    //MARK:--------------------UI--------------------
    func setUI() {
        title = "修改手机号"
        phoneTxt.becomeFirstResponder()
    }
    func addConstraints() {
        
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        codeBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            guard let phone = self.phoneTxt.text, phone.zm.isPhoneNum() else {
                return ZMToast.showToast(title: "请输入正确手机号")
            }
            LoginService.shared.showVerifycation(vc: self) { [unowned self] success in
                if success {
                    LoginAPI.sendCode(["phone" : phone]).rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
                        self.codeTxt.becomeFirstResponder()
                        self.codeBtn.start(time: 60)
                    }).disposed(by: self.disposeBag)
                }
            }
        }).disposed(by: disposeBag)
        
        nextBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            guard let phone = self.phoneTxt.text, phone.zm.isPhoneNum() else {
                return ZMToast.showToast(title: "请输入正确手机号")
            }
            guard let code = self.codeTxt.text, code.count == 6 else {
                return ZMToast.showToast(title: "请输入6位验证码")
            }
            ZMToast.showActivity()
            MineAPI.modifyPhone(["captcha":code,"phone":phone]).rxRequestNullAble(type: Bool.self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                if let data = resp, data {
                    LoginService.shared.loginOut(false)
                    ZMJumpHelper.destroy(FromVC: self, toFirstClass: MineVC.classForCoder(), isContainSelf: true)
                    router.push("xm://main/Login/index")
                    ZMToast.showToast(title: "修改成功，请重新登录")
                }
            }).disposed(by: self.disposeBag)
        }).disposed(by: disposeBag)
    }

    //MARK:--------------------delegate--------------------

}
